// APP参数
window.APP = {
	app_name: '龙信云商铺',
	version_name: '1.0',
	web_root:"http://newapp.cn/",
	api_url: "http://shenql.cn/api/",
	pic_url: "http://shenql.cn/",
	payment: {
		ALIPAY: 3,
		WECHAT: 2,
		UNIONPAY: 4,
		YUE: 1
	}
}
function settime(i, datetime) {
	var tm = format_time(datetime);
	$("#countdown" + i).html('<em >' + tm + "</em>");
	datetime = datetime - 1000;
	if(datetime <= 0) {
		$("#countdown" + i).html("活动已结束");
		return;
	}
	setTimeout(function() {
		settime(i, datetime);
	}, 1000);
}

function format_time(value) {
	//计算出相差天数
	var days = Math.floor(value / (24 * 3600 * 1000))
	//计算出小时数
	var leave1 = value % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000))
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000))
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000)
	return days+'天' + hours + '时' + minutes + '分' + seconds + '秒';
}
Date.prototype.Format = function(fmt)   
	{ //author: meizz   
	  var o = {   
	    "M+" : this.getMonth()+1,                 //月份   
	    "d+" : this.getDate(),                    //日   
	    "h+" : this.getHours(),                   //小时   
	    "m+" : this.getMinutes(),                 //分   
	    "s+" : this.getSeconds(),                 //秒   
	    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
	    "S"  : this.getMilliseconds()             //毫秒   
	  };   
	  if(/(y+)/.test(fmt))   
	    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
	  for(var k in o)   
	    if(new RegExp("("+ k +")").test(fmt))   
	  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
	  return fmt;   
} 
//生成单号
function getSn(){
	var time1 = new Date().Format("yyyyMMddhhmmss");
	var num = Math.random(); //生成0-1的随机码。
	num = Math.round(num * 1e8); //扩大10的8次方倍后取整。
	var sn=time1.toString() + num;
	return sn;
}

/*if(is_weixn()){
	getOpenId();
}*/


function getOpenId() {
	var s=localStorage.getItem('clear');
	if(!s){
		localStorage.clear();
		delCookie('opneid');
	}
	var iswx = is_weixn();
	var access_code = getQueryString("code");
	var member = localStorage.getItem("member");
	var openid=localStorage.getItem("openid");
	if(member&&member['openid']){
		openid=member['openid'];
	}
	if(openid==null||openid=="null"){
			openid="";
	}
	if(iswx && openid == "") {
		if(access_code == null) {
			var fromurl = location.href;
						var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa8273be4e9212fe1&redirect_uri=' + encodeURIComponent(fromurl) + '&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			location.href = url;
		} else {
				$.ajax({
					async: false, 
					type: 'post',
					url: APP.api_url + 'Member/getOpenId',
					data: {
						code: access_code,
						token:'cheshi',
						fromuid:getUrlParam("fromuid")
					},
					success: function(data) {
						var res = JSON.parse(data);
						if(res.code != 200) {
							layer.msg(res.msg);
							return;
						}
						if(res.data){
							localStorage.setItem("member", JSON.stringify(res.data));
						}
						localStorage.setItem("clear",1);
						localStorage.setItem("openid",res.openid);
						
					}
				});
		}
	}else{
		//url_jump("请在微信浏览器中打开","error");
	}
}
//判断是否是微信
function is_weixn() {
	var ua = navigator.userAgent.toLowerCase();
	if(ua.match(/MicroMessenger/i) == "micromessenger") {
		return true;
	} else {
		return false;
	}
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}
// 退出用户
function logout() {
	localStorage.removeItem("member");
	window.location.href = "/member/login.html";
}
// 增加cookie
function addcookie(name, value, expireHours) {
	var cookieString = name + "=" + escape(value) + "; path=/";
	//判断是否设置过期时间  
	if(expireHours > 0) {
		var date = new Date();
		date.setTime(date.getTime + expireHours * 3600 * 1000);
		cookieString = cookieString + "; expire=" + date.toGMTString();
	}
	document.cookie = cookieString;
}
// 获得cookie
function getcookie(name) {
	var strcookie = document.cookie;
	var arrcookie = strcookie.split("; ");
	for(var i = 0; i < arrcookie.length; i++) {
		var arr = arrcookie[i].split("=");
		if(arr[0] == name) return decodeURIComponent(arr[1]); //增加对特殊字符的解析  
	}
	return "";
}
//订单状态：1：未付款；2：拼团中；3：待发货；4：已发货；5：已完成；6：已关闭7:待确认消费8物流不达9交易完成10管理员关闭11客户关闭12点参待消费13点餐确认消费14点餐预约
function getOrderStatus(order_state){
	var status="";
	switch(order_state){
		case 1:status= "未付款";break;
		case 2:status= "拼团中";break;
		case 3:status= "待发货";break;
		case 4:status= "已发货";break;
		case 5:status= "已完成";break;
		case 6:status= "已关闭";break;
		case 7:status= "待确认消费";break;
		case 8:status= "物流不达";break;
		case 9:status= "交易完成";break;
		case 10:status= "系统关闭";break;
		case 11:status= "用户关闭";break;
		case 12:status= "待付款";break;//点餐
		case 13:status= "待确认消费";break;//点餐
		case 14:status= "待付款";break;//预约
		case 15:status= "待确认消费";break;//预约
		case 16:status= "申请退款中";break;
		case 17:status= "退款失败";break;
		case 18:status= "退款成功";break;
		defatult:
		status="未付款";
	}
	return status;
}
// 删除cookie
function delCookie(name) { //删除cookie  
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getcookie(name);
	if(cval != null) document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
}
//获取用户当前地址
function getAddress(){
	
	var script2 = document.createElement("script");
	script2.type = "text/javascript";
	script2.src = "http://developer.baidu.com/map/jsdemo/demo/convertor.js";
	document.body.appendChild(script2);
	
	
	var script1 = document.createElement("script");
	script1.type = "text/javascript";
	script1.src = "http://api.map.baidu.com/api?v=2.0&ak=grTHl4v1H6uGFLChfz0aB0uQG4XWQv0k&callback=my_getAddress";
	document.body.appendChild(script1);
	
}

function my_getAddress(){
	Axis = new Object();
	Axis.longitude = 113.022014;
	Axis.latitude = 25.779124;
	if (navigator.geolocation) {  //调用导航器geolocation函数
        navigator.geolocation.getCurrentPosition(function(position){
        	var latitude = position.coords.latitude;//y，纬度，
			var longitude = position.coords.longitude;//x，经度
			ggPoint = new BMap.Point(longitude,latitude);
			 //地图初始化
		    var bm = new BMap.Map("allmap");
		    bm.centerAndZoom(ggPoint, 15);
		    bm.addControl(new BMap.NavigationControl());
		    
		    //坐标转换完之后的回调函数
		    var convertor = new BMap.Convertor();
	        var pointArr = [];
	        pointArr.push(ggPoint);
	        convertor.translate(pointArr, 1, 5, function(points){
	        	var marker = new BMap.Marker(points);
			    bm.addOverlay(marker);
			    bm.setCenter(points);
			    var point = points['points'][0];
			    Axis.longitude = point.lng;
				Axis.latitude = point.lat;
			    var curWwwPath = window.document.location.href;
			    if(curWwwPath.indexOf(APP.web_root+"index") >= 0 || curWwwPath ==APP.web_root)   
				{   
					//获取详细地址信息
				    var gc = new BMap.Geocoder();  //初始化，Geocoder类
					gc.getLocation(point, function (rs) {
						  var addComp = rs.addressComponents;
					      var province 		= addComp.province;//获取省份
					      var city 			= addComp.city;//获取城市
					      var district 		= addComp.district;//区
					      var street 		= addComp.street;//街
					      var streetNumber 	= addComp.streetNumber //门牌号
					      $("#address").text(street+streetNumber);
		   			}); //进入总显示函数loand，函数名由自己定
				} 
			    
	        });
     	});
    } else {
         alert("您的浏览器不支持地理定位");//不支持
    }
    localStorage.setItem('axis', JSON.stringify(Axis));
}

//图片转化为缩略图路径
function toThumb(pic) {
	var i = pic.lastIndexOf("."); //点的位置
	var postfix = pic.substr(i, pic.length); //后缀
	var thumb = pic.substr(0, i) + "_thumb" + postfix;
	return thumb;
}

function del_event() {
	var del = ca.className('del');
	for(var a = 0; a < del.length; a++) {
		del[a].addEventListener('tap', function() {
			$(this).parent().parent().parent().find('.file-btn').show();
			$(this).parent().remove();
		})
	}
}
/**
 * 上传图片
 * name 存储图片form元素id
 * length 上传张数
 */
function readFile1(input, name, length) {
	var img_list = $(input).parent().find('span').find("img");
	if(input.files && input.files[0]) {
			var reader = new FileReader();
	   		var AllImgExt="image/jpg|image/jpeg|image/png|image/bmp";  
            var extName = input.files[0].type.toLowerCase();//（把路径中的所有字母全部转换为小写）          
            if(AllImgExt.indexOf(extName+"|")==-1)          
            {  
                ErrMsg="该文件类型不允许上传。请上传 "+AllImgExt+" 类型的文件，当前文件类型为"+extName;  
                alert(ErrMsg);  
                return false;  
            }  
		var fd = new FormData();
		  var sendData;
		for(var i = 0; i < input.files.length; i++) {
			var reader = new FileReader();
			reader.readAsDataURL(input.files[i]);
				reader.onload = function (event) {
				    var img = new Image();
				    img.onload = function () {
				    	var canvas = document.createElement("canvas"); 
				    	canvas.width=500;
				    	canvas.height=500*img.height/img.width;
							var ctx = canvas.getContext('2d'); 
							ctx.clearRect(0, 0, canvas.width, canvas.height); 
                            ctx.drawImage(img, 0, 0, 500,500*img.height/img.width);
                            var newImageData=canvas.toDataURL('image/jpeg',0.8);
					        sendData = newImageData.replace("data:"+'image/jpeg'+";base64,",'');
				        	$.post(APP.api_url + "System/upload1",{value:sendData},function(data){  
	                            if(data.code == '200'){  
	                                $("#"+name).val(data.url);
									img_list.attr("src",data.url);
	                            }else{  
	                                layer.msg(data.msg);
	                            }  
                    		}); 
					}
				    img.src = reader.result;
           		}
			
		}
		
	} else {
		alert("抱歉，你的浏览器不支持 FileReader");
	}
}

/**
 * 上传图片
 * name 存储图片form元素id
 * length 上传张数
 */
function readFile(input, name, length) {
	var img_list = $(input).parent().parent().find("div[id='img_list']");
	if(input.files && input.files[0]) {
		var reader = new FileReader();
		var AllImgExt="image/jpg|image/jpeg|image/png|image/bmp";  
        var extName = input.files[0].type.toLowerCase();//（把路径中的所有字母全部转换为小写）          
        if(AllImgExt.indexOf(extName+"|")==-1)          
        {  
            ErrMsg="该文件类型不允许上传。请上传 "+AllImgExt+" 类型的文件，当前文件类型为"+extName;  
            alert(ErrMsg);  
            return false;  
        }  
		var fd = new FormData();
		for(var i = 0; i < input.files.length; i++) {
			var reader = new FileReader();
			console.log(input.files[i]);
			reader.readAsDataURL(input.files[i]);
			fd.append(i, input.files[i]);　　　　
		}
		$.ajax({
			url: APP.api_url + "System/upload",
			type: 'POST',
			data: fd,
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function(returndata) {
				var res = JSON.parse(returndata).files[0].url;
				var img_url1 = res.substr(2, res.length);
				var innerHTML = '<div class="images-item" style="width:150px;margin:0 auto;">' +
						'	<span class="del" style="font-size:18px;">×</span>' +
					'	<img style="width: 80px;height: 80px; margin:0 auto;" src="' + APP.pic_url + img_url1 + '"/>' +
					'	<input type="hidden" name="' + name + '" value="' + img_url1 + '"/>' +
					'</div>';
				img_list.append(innerHTML);
				del_event();
				if(img_list.find('.images-item').size() >= length) {
					$(input).parent(".file-btn").hide();
				}
			},
			error: function(returndata) {}
		});
	} else {
		alert("抱歉，你的浏览器不支持 FileReader");
	}
}


/**
 * url参数获取
 * @param  name 参数名
 */
function getUrlParam(pname) {
	var name, value;
	var str = location.href; //取得整个地址栏
	var num = str.indexOf("?")
	str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
	var arr = str.split("&"); //各个参数放到数组里
	for(var i = 0; i < arr.length; i++) {
		num = arr[i].indexOf("=");
		if(num > 0) {
			name = arr[i].substring(0, num);
			value = arr[i].substr(num + 1);
			if(pname == name) {
				return value;
			}
		}
	}
}
/**
 * 新增url中参数值
 */
function setParam(param,value){
    var query = location.search.substring(1);
    var p = new RegExp("(^|)" + param + "=([^&]*)(|$)");
    if(p.test(query)){
        //query = query.replace(p,"$1="+value);
        var firstParam=query.split(param)[0];
        var secondParam=query.split(param)[1];
        if(secondParam.indexOf("&")>-1){
            var lastPraam=secondParam.split("&")[1];
            return  '?'+firstParam+'&'+param+'='+value+'&'+lastPraam;
        }else{
            if(firstParam){
                return '?'+firstParam+'&'+param+'='+value;
            }else{
                return '?'+param+'='+value;
            }
        }
    }else{
        if(query == ''){
            return '?'+param+'='+value;
        }else{
            return '?'+query+'&'+param+'='+value;
        }
    }
}
/**
 * 修改url中参数的值
 */
function replaceParamVal(paramName,replaceWith) {
    var oUrl = this.location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    var nUrl = oUrl.replace(re,paramName+'='+replaceWith);
    this.location = nUrl;
}

//更新用户localstorm
function update_Member(member) {
	localStorage.setItem('member', JSON.stringify(member));
}
//获得当前登录用户ID
function getUid() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['id'];
}
//获取保存用户的某个属性信息
function getValueByName(name){
	var member = JSON.parse(localStorage.getItem('member'));
	return member[name];
}
function checkLogin() {
	var member=localStorage.getItem('member');
	if(member==null){
		window.location="/store/shop/login.html";
	}
}

//检查用户登录,登陆后跳回源页面
function back_login(){
	//检查用户登录
	var user = JSON.parse(localStorage.getItem('member'));
		if(!user){
			layer.msg('请先登录！', {time: 1000}, function() {
				sessionStorage.setItem("source_page", location.href);
				location.href='/member/login.html';
				});
		}else{
			return true;
		}
}


function getUserMobile() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['mobile'];
}



//简单页面跳转
function url_jump(data, url) {
	layer.msg(data.msg, {
		icon: 1,
		time: 1000 //2秒关闭（如果不配置，默认是3秒）
	}, function() {
		if(data.code == 200) {
			location.href = url + '.html';
		}
	});
}
function jump(msg,url){
	layer.msg(msg, {
		icon: 1,
		time: 1000 //2秒关闭（如果不配置，默认是3秒）
	}, function() {
		location.href = url;
	});
}
//页面跳转
function url_data(data) {
	ca.newInterface({
		url: data + '.html',
		id: data,
	});
}

//获取用户token
function get_token() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['token'];
}

function login_jump(url) {
	var login_user = getUid();
	if(!login_user) {
		ca.prompt('请先登录');
		setTimeout(function() {
			url_jump("login");
		}, 1000);
	} else {
		url_jump(url);
	}
}
//注册支付宝新用户
function alipay_user(access_code,fromuid) {
	$.ajax({
		//type: 'post',
		async: false, 
		url: APP.api_url + 'wallet/cut_user_alibyid',
		data: {
			code: access_code,
			fromuid: fromuid,
			token :'cheshi'
		},
		success: function(data) {
			if(data.code == 200) {
				localStorage.setItem('member', JSON.stringify(data.data));
				localStorage.setItem('alipay_id', JSON.stringify(data.data.alipay_id));
			} else {
				layer.msg(data.msg);
			}
		}
	});
}
//注册微信新用户
function open_user(access_code,fromuid) {
	$.ajax({
		//type: 'post',
		url: APP.api_url + 'wallet/cut_user_openId',
		data: {
			code: access_code,
			fromuid: fromuid,
			token :'cheshi'
		},
		success: function(data) {
			if(data.code == 200) {
				localStorage.setItem('member', JSON.stringify(data.data));
				addcookie("openid", data.data.openid);
			} else {
				layer.msg(data.msg);
			}
		}
	});
}


//更新当前用户信息
function cut_member_info(){
	$.ajax({
		//type: 'post',
		async: false,
		url: APP.api_url + 'wallet/cut_member_info',
		data: {
			uid: getUid(),
			token: get_token()
		},
		success: function(data) {
			if(data.code == 200) {
				localStorage.setItem('member', JSON.stringify(data.data));
				localStorage.setItem("openid",data.data.openid);
			} else {
				layer.msg(data.msg);
			}
		}
	});
}
//获取根据openid查找用户,不存在则创建用户
	function member_by_openid(openid,fromuid){
		$.ajax({
			//type: 'post',
			async: false, 
			url: APP.api_url + 'wallet/member_by_openid',
			data: {
				openid		: openid,
				fromuid		:fromuid,
				token 		:'cheshi'
			},
			success: function(data) {
				localStorage.setItem('member', JSON.stringify(data.data));
			}
		});
	}
	
//用户图片
function user_tupian(thumb,moren){
	var tupian = moren;
                           
    if(thumb && thumb.length>2){
        if(thumb.indexOf("wx.qlogo")>0 || thumb.indexOf("shanghai.aliyuncs")>0){
	        tupian = thumb;
	    }else{
	        tupian = APP.pic_url+thumb;
	    }
    }else{
    	tupian = APP.web_root+moren;
    }
    return tupian;
}
